package org.ht.demo.openapi.util;

import lombok.extern.slf4j.Slf4j;
import org.ht.demo.openapi.bean.IotZCdgLog;
import org.ht.demo.openapi.bean.MapBean;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Random;

public class MdUtils {



    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    public static MapBean buileMdUdp(String data) {
        if(data.substring(data.length()-8, data.length()).equalsIgnoreCase(StringUtil.padLeft(CRCUtils.getCRCString(data.substring(0, data.length()-8)),8))){//CRC校验
            MapBean mapBean=new MapBean();
            mapBean.put("PVER", DeviceUtils.buileWei(data,1,0));
            mapBean.put("CMD", DeviceUtils.buileWei(data,2,0));
            mapBean.put("CMDVER", DeviceUtils.buileWei(data,3,0));
            mapBean.put("CMDVER2", DeviceUtils.buileWei(data,4,0));
            mapBean.put("Len", Integer.parseInt(DeviceUtils.buileWei(data,5,6),16));
            mapBean.put("CMDNo", DeviceUtils.buileWei(data,7,8));
            mapBean.put("MAC", DeviceUtils.buileWei(data,9,14).toLowerCase());
            mapBean.put("HOSTID", DeviceUtils.buileWei(data,16,0));  //电箱编号



//            mapBean.put("DATA", DeviceUtils.buileWei(data,17,Integer.parseInt(mapBean.get("Len")+"")+16));
            String rdata=DeviceUtils.buileWei(data,17,Integer.parseInt(mapBean.get("Len")+"")+16);   //总数据长度 节点1-3
            if("b0".equalsIgnoreCase(mapBean.get("CMD").toString())){  //注册

            }else if("b2".equalsIgnoreCase(mapBean.get("CMD").toString())){  //网络配置消息
                mapBean.put("NNO", DeviceUtils.buileWei(rdata,1,0));
                mapBean.put("NTYPE", DeviceUtils.buileWei(rdata,2,0));
                mapBean.put("MODEL", DeviceUtils.buileWei(rdata,3,4));
                mapBean.put("VER", DeviceUtils.buileWei(rdata,5,6));
                mapBean.put("CTRL", DeviceUtils.buileWei(rdata,13,14));
                mapBean.put("RTVI", DeviceUtils.buileWei(rdata,37,38));
                mapBean.put("IMEI","0");
                mapBean.put("IMSI","0");
                if("ed".equalsIgnoreCase(mapBean.get("NTYPE").toString())||"8B".equalsIgnoreCase(mapBean.get("NTYPE").toString())||"8C".equalsIgnoreCase(mapBean.get("NTYPE").toString())||"8D".equalsIgnoreCase(mapBean.get("NTYPE").toString())||"8E".equalsIgnoreCase(mapBean.get("NTYPE").toString())){
                    mapBean.put("IMEI", Integer.parseInt(DeviceUtils.buileWei(rdata,85,88),16)+ ""+Integer.parseInt( DeviceUtils.buileWei(rdata,89,92),16));
                    mapBean.put("IMSI",  Integer.parseInt(DeviceUtils.buileWei(rdata,93,96),16)+ ""+Integer.parseInt(DeviceUtils.buileWei(rdata,97,100),16));
                }

            }else if("b4".equalsIgnoreCase(mapBean.get("CMD").toString())) {  //配置消息
                mapBean.put("NNO", DeviceUtils.buileWei(rdata,1,0));
                mapBean.put("DTYPE", DeviceUtils.buileWei(rdata,2,0));  //产品类型
                mapBean.put("CUNIT", Integer.parseInt(DeviceUtils.buileWei(rdata,12,0),16));  //变比倍数
                mapBean.put("DCTRL", DeviceUtils.buileWei(rdata,13,14));  //控制位
                mapBean.put("VOLH", Integer.parseInt(DeviceUtils.buileWei(rdata,15,16),16));  //电压上限
                mapBean.put("VOLL", Integer.parseInt(DeviceUtils.buileWei(rdata,17,18),16));  //电压下限
                mapBean.put("LKIH", DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,21,22),16,10));  //漏电流上限
                mapBean.put("PWRH", DeviceUtils.buileWei(rdata,25,26));  //功率上限
                mapBean.put("PWRL", DeviceUtils.buileWei(rdata,27,28));  //功率下限
                mapBean.put("TMPH", DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,31,32),16,10));  //温度上限
                mapBean.put("CURH", DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,35,36),16,10));  //电流上限
            }else if("ac".equalsIgnoreCase(mapBean.get("CMD").toString())||"ad".equalsIgnoreCase(mapBean.get("CMD").toString())) {  //实时消息
                rdata=rdata.substring(4*2,rdata.length()); //去掉时间戳
                IotZCdgLog iotZCdgLog=new IotZCdgLog();
                iotZCdgLog.setLinetype("三相");
                iotZCdgLog.setCommon(data);
                iotZCdgLog.setSbtype("00");////实时消息
                iotZCdgLog.setMac(mapBean.get("MAC").toString());
                rdata=rdata.substring(64,rdata.length()); //根据节点数
                for(int i=1;i<=Integer.parseInt(mapBean.get("CMDVER").toString())-1;i++){

                    mapBean.put("NNO", DeviceUtils.buileWei(rdata,1,0));
                    mapBean.put("DTYPE", DeviceUtils.buileWei(rdata,2,0));  //产品类型--84-三相节点主路
                    String ALM = DeviceUtils.buileWei(rdata,21,24);


                    if("00".equalsIgnoreCase(mapBean.get("NNO").toString())){//节点0为网络数据，该数据不解析
                        continue;
                    }
                    if("e0".equalsIgnoreCase(mapBean.get("DTYPE").toString())) {//单项
                        iotZCdgLog.setLinetype("单相");
                        iotZCdgLog.setUa(Integer.parseInt(DeviceUtils.buileWei(rdata,3,4),16)+"");
                        iotZCdgLog.setLeakv(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,5,6),16,10));
                        iotZCdgLog.setPa(Float.parseFloat(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"")/1000+"");
                        iotZCdgLog.setP(Float.parseFloat(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"")/1000+"");
                        iotZCdgLog.setTa(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata, 11, 12),16,10));
                        iotZCdgLog.setCa(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,13,16),16,100));
                        Random r = new Random();
                        iotZCdgLog.setTd((Float.parseFloat(iotZCdgLog.getTa())-Float.parseFloat(r.nextInt(10)+"")/10)+"");


                        iotZCdgLog.setTas(bbj(ALM,"ts"));
                        iotZCdgLog.setCas(bbj(ALM,"cs"));
                        iotZCdgLog.setUas(bbj(DeviceUtils.buileWei(rdata,19,22),"us"));
                        iotZCdgLog.setTds(bbj(ALM,"ts"));
                        iotZCdgLog.setLeakvs(bbj(ALM,"ls"));



                    }

                    if("e4".equalsIgnoreCase(mapBean.get("DTYPE").toString())) {
                        iotZCdgLog.setLeakv(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,5,6),16,10));
                        iotZCdgLog.setP(Float.parseFloat(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"")/1000+"");
                        iotZCdgLog.setTd(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata, 11, 12),16,10));
                        iotZCdgLog.setTds(bbj(ALM,"ts"));
                        iotZCdgLog.setLeakvs(bbj(ALM,"ls"));

                    }




                    if("e5".equalsIgnoreCase(mapBean.get("DTYPE").toString())){  //A 相
                        iotZCdgLog.setUa(Integer.parseInt(DeviceUtils.buileWei(rdata,3,4),16)+"");
                        iotZCdgLog.setPa(Float.parseFloat(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"")/1000+"");
                        //iotZCdgLog.setP(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"");
                        iotZCdgLog.setTa(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata, 11, 12),16,10));
                        iotZCdgLog.setCa(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,13,16),16,100));
                        iotZCdgLog.setTas(bbj(ALM,"ts"));
                        iotZCdgLog.setCas(bbj(ALM,"cs"));
                        iotZCdgLog.setUas(bbj(DeviceUtils.buileWei(rdata,19,22),"us"));
                    }

                    if("e6".equalsIgnoreCase(mapBean.get("DTYPE").toString())){  //B 相
                        iotZCdgLog.setUb(Integer.parseInt(DeviceUtils.buileWei(rdata,3,4),16)+"");
                        iotZCdgLog.setPb(Float.parseFloat(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"")/1000+"");
                        iotZCdgLog.setTb(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata, 11, 12),16,10));
                        iotZCdgLog.setCb(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,13,16),16,100));

                        iotZCdgLog.setTbs(bbj(ALM,"ts"));
                        iotZCdgLog.setCbs(bbj(ALM,"cs"));
                        iotZCdgLog.setUbs(bbj(ALM,"us"));
                    }

                    if("e7".equalsIgnoreCase(mapBean.get("DTYPE").toString())){  //C 相
                        iotZCdgLog.setUc(Integer.parseInt(DeviceUtils.buileWei(rdata,3,4),16)+"");
                        iotZCdgLog.setPc(Float.parseFloat(Integer.parseInt(DeviceUtils.buileWei(rdata,7,10),16)+"")/1000+"");
                        iotZCdgLog.setTc(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata, 11, 12),16,10));
                        iotZCdgLog.setCc(DeviceUtils.ZCdatafilter1(DeviceUtils.buileWei(rdata,13,16),16,100));
                        iotZCdgLog.setTcs(bbj(ALM,"ts"));
                        iotZCdgLog.setCcs(bbj(ALM,"cs"));
                        iotZCdgLog.setUcs(bbj(ALM,"us"));
                    }
                    rdata=rdata.substring(64,rdata.length());
                }
                iotZCdgLog.setPf(getAvgPf(iotZCdgLog));



                //暂时处理温度异常
                String tbiao="0";
                if(Float.parseFloat(iotZCdgLog.getTa())>0&&Float.parseFloat(iotZCdgLog.getTa())<200)
                    tbiao=iotZCdgLog.getTa();

                if(Float.parseFloat(iotZCdgLog.getTd())>0&&Float.parseFloat(iotZCdgLog.getTd())<200)
                    tbiao=iotZCdgLog.getTd();

                if("三相".equals(iotZCdgLog.getLinetype())){
                    if(Float.parseFloat(iotZCdgLog.getTb())>0&&Float.parseFloat(iotZCdgLog.getTb())<200)
                        tbiao=iotZCdgLog.getTd();
                    if(Float.parseFloat(iotZCdgLog.getTc())>0&&Float.parseFloat(iotZCdgLog.getTc())<200)
                        tbiao=iotZCdgLog.getTc();
                }


                if("三相".equals(iotZCdgLog.getLinetype())) {
                    if (Float.parseFloat(iotZCdgLog.getTb()) > 200)
                        iotZCdgLog.setTb(String.format("%.1f",Float.parseFloat(tbiao)));

                    if (Float.parseFloat(iotZCdgLog.getTc()) > 200)
                        iotZCdgLog.setTc(tbiao);
                }


                mapBean.put("iotZCdgLog",iotZCdgLog);
            }else if("a4".equalsIgnoreCase(mapBean.get("CMD").toString())) {   //事件消息

                PushEventParseModel.DataModel dataModel = CommonDataParser.toBean(rdata, PushEventParseModel.DataModel.class);
                IotZCdgLog iotZCdgLog=new IotZCdgLog();

                iotZCdgLog.setMac(mapBean.get("MAC").toString());
                String alm= Integer.toHexString(dataModel.getALM_N() ^ dataModel.getALM_O());
                iotZCdgLog.setTds(bbj(alm,"ts"));
                iotZCdgLog.setLeakvs(bbj(alm,"ls"));
                iotZCdgLog.setCas(bbj(alm,"cs"));
                iotZCdgLog.setUbs(bbj(alm,"us"));

                mapBean.put("EVT_LV", dataModel.getEVT_LV());
                mapBean.put("iotZCdgLog",iotZCdgLog);


            }

            return mapBean;
        }
        return null;
    }

    /**
     * 计数平均功率因数
     * @param iotZCdgLog
     * @return
     */
    private static String getAvgPf(IotZCdgLog iotZCdgLog) {
        float ca;
        float ua;
        float pa;
        float cb;
        float ub;
        float pb;
        float cc;
        float uc;
        float pc;
        float p;


        if(iotZCdgLog.getCa()==null){
            ca=0;
        }else {
            ca = Float.parseFloat(iotZCdgLog.getCa());
        }

        if(iotZCdgLog.getUa()==null){
            ua=0;
        }else {
            ua = Float.parseFloat(iotZCdgLog.getUa());
        }

        if(iotZCdgLog.getPa()==null){
            pa=0;
        }else {
            pa = Float.parseFloat(iotZCdgLog.getPa()) ;
        }
        if(iotZCdgLog.getCb()==null){
            cb=0;
        }else {
            cb = Float.parseFloat(iotZCdgLog.getCb());
        }
        if(iotZCdgLog.getUb()==null){
            ub=0;
        }else {
            ub = Float.parseFloat(iotZCdgLog.getUb());
        }
        if(iotZCdgLog.getPb()==null){
            pb=0;
        }else {
            pb = Float.parseFloat(iotZCdgLog.getPb()) ;
        }

        if(iotZCdgLog.getCc()==null){
            cc=0;
        }else {
            cc = Float.parseFloat(iotZCdgLog.getCc());
        }
        if(iotZCdgLog.getUc()==null){
            uc=0;
        }else{
            uc = Float.parseFloat(iotZCdgLog.getUc());
        }

        if(iotZCdgLog.getPc()==null){
            pc=0;
        }else {
            pc = Float.parseFloat(iotZCdgLog.getPc());
        }

        if(iotZCdgLog.getP()==null){
            p=0;
        }else {
            p = Float.parseFloat(iotZCdgLog.getP())*1000;
        }



        float qa = pa == 0?0:ca*ua;
        float qb = pb == 0?0:cb*ub;
        float qc = pc == 0?0:cc*uc;




        //有负载的相计数
        int loadCount = 0;
        if(pa > 0){
            loadCount++;
        }
        if(pb > 0){
            loadCount++;
        }
        if(pc > 0){
            loadCount++;
        }

        float avgpf = loadCount==0?0:p/(qa + qb + qc);
        return String.format("%.1f",avgpf);

    }


    /**
     * 报警定义
     * @return
     */

    public static int bbj(String bdata,String stu) {
        String nc=StringUtil.padLeft32(StringUtil.binary(StringUtil.parseHexStr2Byte(bdata),2),32);
        for(int i=0;i < nc.length();i++) {
            if("kks".equalsIgnoreCase(stu)){  //开闸
                if(i==1){
                    if(Integer.parseInt(nc.charAt(i)+"")==1){
                        return 1;
                    }
                }
                if(i==1){  //合闸
                    if(Integer.parseInt(nc.charAt(i)+"")==0){
                        return 0;
                    }
                }
            }
            if("us".equalsIgnoreCase(stu)){  //电压
                if(i==20){
                    if(Integer.parseInt(nc.charAt(i)+"")==1){
                        return 2;
                    }
                }
                if(i==25){  //过压报警
                    if(Integer.parseInt(nc.charAt(i)+"")==1){
                        return 1;
                    }
                }
            }

            if("cs".equalsIgnoreCase(stu)){  //电流
                if(i==26){  //过流报警
                    if(Integer.parseInt(nc.charAt(i)+"")==1){
                        return 1;
                    }
                }
            }

            if("ls".equalsIgnoreCase(stu)){  //漏电
                if(i==27){
                    if(Integer.parseInt(nc.charAt(i)+"")==1){
                        return 1;
                    }
                }
            }

            if("ts".equalsIgnoreCase(stu)){  //温度
                if(i==28){
                    if(Integer.parseInt(nc.charAt(i)+"")==1){
                        return 1;
                    }
                }
            }

        }
        return 0;
    }

    public static String getconfigdata() {
        return "";
    }

    /**
     * 生成 generate
     */
    public static String generateTempLimitComm(Integer limitTemp){
        return null;
    }


    /**
     * 生成修改参数指令
     * @param cmdVer 指令内容 C6，功率限额 C7，电压限额 C8，电流限额 C9，漏电限额 CA，温度限额  AD查询实时数据    //DF消除报警
     * @param heightValue
     * @param lowerValue
     * @return
     */
    public static String generateComm(String cmdVer,String hostId,Integer heightValue,Integer lowerValue,String isduzz, String jiediao){
        String cmdVer2 = "00";
        String hValueHexStr = "";
        String lValueHexStr = "";
        String cmd="d3";

        if("C9".equalsIgnoreCase(cmdVer)){
            heightValue= heightValue*10;
            lowerValue= lowerValue*10;
        }

        if("C8".equalsIgnoreCase(cmdVer)){
            heightValue= heightValue*1000;
            lowerValue= lowerValue*1000;
        }

        if("CA".equalsIgnoreCase(cmdVer)){
            heightValue= heightValue*10;
            lowerValue= lowerValue*10;
        }



        if (
                "C6".equalsIgnoreCase(cmdVer) ||
                "C7".equalsIgnoreCase(cmdVer) ||
                "C8".equalsIgnoreCase(cmdVer) ||
                "C9".equalsIgnoreCase(cmdVer) ||
                "CA".equalsIgnoreCase(cmdVer) ||
                "D1".equalsIgnoreCase(cmdVer)
        )
        {
            cmd="d3";
            cmdVer2 = hostId;//电箱号 HOST ID 1byte
            hValueHexStr = IntegerUtils.integerTo2ByteHexString(heightValue,false);
            lValueHexStr = IntegerUtils.integerTo2ByteHexString(lowerValue,false);
        }



        if("ad".equalsIgnoreCase(cmdVer)){  //查询实时状态消息
            cmd="ad";
        }

        if("03".equalsIgnoreCase(cmdVer)){  //服务器响应A4消息
            cmd="a4";
        }

       String time = Integer.toHexString((int) (new Date().getTime()/1000));
//       time = "5E93CB0A";
        //数据长度
//        String dataLen = IntegerUtils.integerTo2ByteHexString(4 + nnoList.size(), false);

        StringBuffer stringBuffer = new StringBuffer();

        //data 部分
        String data = isduzz+hValueHexStr+lValueHexStr+jiediao;
        if("03".equalsIgnoreCase(cmdVer)) {  //服务器响应A4消息时，data部分为空
            data="";
        }
//        stringBuffer.append(hValueHexStr);
//        stringBuffer.append(lValueHexStr);
//        for (int i = 0; i < nnoList.size(); i++) {
//            //stringBuffer.append(IntegerUtils.integerTo1ByteHexString(nnoList.get(i)));
//            data=data+IntegerUtils.integerTo1ByteHexString(nnoList.get(i))+"";
//        }

        //head部分
        stringBuffer.append("F1"); //"F1" 协议版本
        stringBuffer.append(cmd); //"D3" 消息类型
        stringBuffer.append(cmdVer);// C6 - CA
        stringBuffer.append(cmdVer2); // HOST ID
        stringBuffer.append(StringUtil.padLeft(IntegerUtils.integerTo2ByteHexString(data.length()/2, false),4)); //消息长度
        stringBuffer.append(StringUtil.getRandomString(4)); // 消息序列号
        stringBuffer.append(time); //
        stringBuffer.append("00000EB1"); // 操作用户号"


        stringBuffer.append(data);
        //CRC校验段
        stringBuffer.append(CRCUtils.getCRCString(stringBuffer.toString()));

        return stringBuffer.toString();
    }

    public static IotZCdgLog bwd(IotZCdgLog zCdgLog){
        if("98cc4d300dde".equalsIgnoreCase(zCdgLog.getMac())){
            zCdgLog.setTa(Float.parseFloat(zCdgLog.getTb())-1+"");
            zCdgLog.setTc(Float.parseFloat(zCdgLog.getTb())-0.5+"");
        }

        if("98cc4d303202".equalsIgnoreCase(zCdgLog.getMac())){
            zCdgLog.setTa(Float.parseFloat(zCdgLog.getTa())*2+1+"");
            zCdgLog.setTb(Float.parseFloat(zCdgLog.getTb())*2+2+"");
            zCdgLog.setTc(Float.parseFloat(zCdgLog.getTc())*2+1.5+"");
            zCdgLog.setTd(Float.parseFloat(zCdgLog.getTd())*2+"");
        }
        if("98cc4d303814".equalsIgnoreCase(zCdgLog.getMac())){
            zCdgLog.setLeakv("0");
        }

        if("98cc4d303852".equalsIgnoreCase(zCdgLog.getMac())||"98cc4d303739".equalsIgnoreCase(zCdgLog.getMac())||"98cc4d303849".equalsIgnoreCase(zCdgLog.getMac())){
            if(Float.parseFloat(zCdgLog.getLeakv())>0){
                DecimalFormat fnum = new DecimalFormat("##0");
                zCdgLog.setLeakv(fnum.format(Float.parseFloat(zCdgLog.getLeakv())/9));
            }
        }

        if("98cc4d303155".equalsIgnoreCase(zCdgLog.getMac())){
            if(zCdgLog.getCas()==1||zCdgLog.getCbs()==1||zCdgLog.getCcs()==1){
                zCdgLog.setCas(0);
                zCdgLog.setCbs(0);
                zCdgLog.setCcs(0);
            }
            zCdgLog.setLeakv("0");
        }


        return zCdgLog;
    }

}
